(function () {
  'use strict';
  var VueTreeItem = Vue.extend({
    template: '<li :class="{parent_li: node.isParent}">' +
    '<i v-if="node.isParent" :click="toggle(node)" class="icon icon-open-state" :class=\'{"icon-chevron-right": !node.isOpen, "icon-chevron-down": node.isOpen}\'></i>' +
    '<span :title="node.title" >' +
    '<i v-if="showIcon(node)" :class="nodeClass(node)" ></i> {{node.name}}</span>' +
    '<span v-for="btn in node.buttons" class="label" :class="getBtnClass(btn)" type="button"  style="float:right"  :click="btnClick(btn, node)">' +
    '<i :class="btn.icon"></i></span>' +
    '<ul v-show="node.isOpen">' +
    '<li v-show="node.showLoading && node._loading"><i class="fa fa-spinner fa-pulse"></i></li>' +
    '<vue-tree-item v-for="item in node.children" :node="item"></vue-tree-item>' +
    '</ul>' +
    '</li>',
    props: {
      node: {
        type: Object
      }
    },
    methods: {
      showIcon: function (node) {
        return node.icon || node.openedIcon || node.closedIcon;
      },
      nodeClass: function (node) {
        if (node.isOpen) {
          return node.openedIcon || node.icon;
        } else {
          return node.closedIcon || node.icon;
        }
      },
      getBtnClass: function (icon) {
        var btnClass = "";
        if (typeof (icon.btnClass) != "undefined") {
          btnClass = icon.btnClass;
        } else {
          btnClass = "label label-success";
        }
        return btnClass;
      },
      toggle: function (node) {
        if (node.hasOwnProperty('isOpen')) {
          node.isOpen = !node.isOpen;
        } else {
          Vue.set(node, 'isOpen', true);
        }
      },
      btnClick: function (btn, node) {
        if (typeof btn.click === 'function') {
          btn.click(node);
        }
      }/*,
      nodeClickFun: function (node) {
        if (typeof node.nodeClick === 'function') {
          node.nodeClick(node);
          console.log(node);
        }

      }*/
    },
    watch: {
      'node.isOpen': function (val) {
        if (!this.node.hasOwnProperty('_loading')) {
          Vue.set(this.node, '_loading', false);
        }
        if (val) {
          if (typeof this.node.onOpened === 'function') {
            this.node.onOpened(this.node);
          }
        } else {
          if (typeof this.node.onClosed === 'function') {
            this.node.onClosed(this.node);
          }
        }
      }
    }
  });
  Vue.component('vue-tree-item', VueTreeItem);

  var VueTree = Vue.extend({
    template: '<div class="vue-tree"><ul>' +
    '<tree-item :node.sync="option.root"></tree-item>' +
    '</ul></div>',
    props: {
      option: {
        type: Object
      }
    },
    components: {
      'tree-item': VueTreeItem
    }
  });
  Vue.component('vue-tree', VueTree);
})();
